import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:whatsapp_messenger/common/helper/show_alert_dialog.dart';
import 'package:whatsapp_messenger/common/helper/show_loading_dialog.dart';
import 'package:whatsapp_messenger/common/models/response_model.dart';
import 'package:whatsapp_messenger/common/models/user_model.dart';
import 'package:whatsapp_messenger/common/routes/routes.dart';

final authRepositoryApiProvider = Provider(
  (ref) {
    return AuthRepositoryApi();
  },
);

class AuthRepositoryApi {
  Dio dio = Dio();
  final String baseUrl = "http://192.168.31.223:8080";

  Stream<UserModel> getUserPresenceStatus({required String uid}) {
    final streamController = StreamController<UserModel>();
    // 模拟异步请求数据
    Future.delayed(Duration(seconds: 2), () {
      streamController.add(
        UserModel(
          username: "username",
          uid: uid,
          profileImageUrl: "profileImageUrl",
          active: true,
          lastSeen: 0,
          phoneNumber: "0",
          groupId: [],
        ),
      );
    });
    // 关闭StreamController
    streamController.close();
    // 返回Stream
    return streamController.stream;
  }

  void updateUserPresence() async {}

  Future<UserModel?> getCurrentUserInfo() async {
    UserModel? user;

    // final userInfo =
    //     await firestore.collection('users').doc(auth.currentUser?.uid).get();
    // if (userInfo.data() == null) return user;
    // user = UserModel.fromMap(userInfo.data()!);
    return user;
  }

  void saveUserInfoToFirestore({
    required String username,
    required var profileImage,
    required ProviderRef ref,
    required BuildContext context,
    required bool mounted,
  }) async {}

  void verifySmsCode({
    required BuildContext context,
    required String phoneNumber,
    required String smsCodeId,
    required String smsCode,
    required bool mounted,
  }) async {
    try {
      showLoadingDialog(
        context: context,
        message: 'Verifiying code ...',
      );

      // TODO 请求后端 验证验证码是否正确
      Response response = await dio.post(baseUrl + "/api/v1/user/checkCode",
          data: {"phoneNumber": phoneNumber, "code": smsCode});
      ResponseModel responseModel = ResponseModel.fromJson(response.data);

      if (responseModel.status == "SUCCESS" && responseModel.data == true) {
        UserModel? user = await getCurrentUserInfo();
        if (!mounted) return;
        Navigator.of(context).pushNamedAndRemoveUntil(
            Routes.userInfo, (route) => false,
            arguments: {
              "phoneNumber": phoneNumber,
              "profileImageUrl": user?.profileImageUrl,
            });
      }
    } catch (ex) {
      Navigator.pop(context);
      showAlertDialog(context: context, message: ex.toString());
    }
  }

  void sendSmsCode({
    required BuildContext context,
    required String phoneNumber,
  }) async {
    showLoadingDialog(
      context: context,
      message: '发送验证码到 $phoneNumber',
    );
    try {
      Response response = await dio.post(baseUrl + "/api/v1/user/code",
          data: {"phoneNumber": phoneNumber});
      ResponseModel responseModel = ResponseModel.fromJson(response.data);
      if (responseModel.status == "SUCCESS") {
        Navigator.of(context).pushNamedAndRemoveUntil(
          Routes.verification,
          (route) => false,
          arguments: {
            'phoneNumber': phoneNumber,
            'smsCodeId': responseModel.data,
          },
        );
      }
    } catch (ex) {
      Navigator.pop(context);
      showAlertDialog(context: context, message: ex.toString());
    }
  }
}
